package controller

import (
	"errors"
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"

	"bluebell/dao/mysql"
	"bluebell/logic"
	"bluebell/models"
	"bluebell/pkg/argon"
	"bluebell/pkg/snowflake"
)
// 用户注册
func SignUpHandler(c *gin.Context) {
	//1.获取参数
	var user models.User
	if err := c.ShouldBind(&user);err != nil{
		errs, ok := err.(validator.ValidationErrors)
		if !ok{
			if errors.Is(err, mysql.ErrorUserExits){
				ResponseError(c, CodeUserExits)
				return
			}
			ResponseError(c, CodeServerBusy)
			
			return
		}
		zap.L().Error("sign up invalid param", zap.Error(err))
		ResponseErrorWidthMsg(c, CodeInvalidParam,removeTopStruct(errs.Translate(trans)))
		
		return 
	}
	userid, _ := snowflake.GetID()
	user.UserID = int(userid)
	hasaPassword := argon.HasPassWord(user.PassWord)
	user.PassWord = hasaPassword
	//2.业务逻辑处理
	err := logic.SignUp(user)
	if err != nil{
		ResponseError(c, CodeUserExits)
		
		return
	}
	//3.返回响应
	ResponseSuccess(c,user)

}

// 用户登录
func UserLogin(c *gin.Context){
	//1.获取参数
	var loginForm  *models.UserLoginForm
	err := c.ShouldBind(&loginForm)
	if err != nil{
		errs, ok := err.(validator.ValidationErrors)
		if !ok{
			ResponseError(c, CodeInvalidParam)
			return
		}
		zap.L().Error("login invalid param", zap.Error(err))
		ResponseErrorWidthMsg(c, CodeInvalidParam,removeTopStruct(errs.Translate(trans)))
		
		return 
	}

    //2.处理业务逻辑
	token,err := logic.UserLogin(loginForm)
	fmt.Println(token,"1111")
	if err != nil{
		if errors.Is(err,mysql.ErrorUserNotExits){
			ResponseError(c, CodeUserNotExits)
			return 
		}
		ResponseErrorWidthMsg(c, CodeUserNotExits,err.Error())
		return
	}
	fmt.Println(token)
    //3.返回相应
	ResponseSuccess(c,token)
	
}
